package ua.com.globallogic.basecamp.krasnyanskiy.FileManager;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static java.lang.System.getProperties;
import static java.lang.System.out;

class ConsoleFileManager implements FileManager {
    private File currentDir = new File(getProperties().getProperty("user.dir"));

    @Override
    public void changeDirectory(String path) {
        if (path == null) {
            out.println("Wrong command!");
            return;
        }
        File tmp = new File(path);
        currentDir = tmp.isDirectory() ? tmp : null;
        out.println(currentDir == null ? "Can't find a directory" : currentDir);
    }

    @Override
    public void createFile(String fileName) {
        try {
            if (new File(currentDir, fileName).createNewFile()) {
                out.println("ok");
            }
        } catch (IOException e) {
            out.println("Sorry! Can't create a file");
        }
    }

    @Override
    public void createDirectory(String fileDirectory) {
        if (new File(currentDir, fileDirectory).mkdir()) {
            out.println("ok");
        } else {
            out.println("Sorry! Can't create a directory");
        }
    }

    @Override
    public void setParentDirectory() {
        String path = currentDir.getParent();
        if (path != null) currentDir = new File(path);
        out.println(currentDir);
    }

    @Override
    public Collection<File> getDirectoryStructure() {
        List<File> files = Arrays.asList(currentDir.listFiles());
        // Print
        for (File file : files) {
            if (file.isFile()) {
                out.println("file = " + file.getName() + ", size = " + file.length());
            }
        }
        return files;
    }

    @Override
    public Collection<File> getDirectoryStructure(String path) {
        changeDirectory(path);
        List<File> files = Arrays.asList(currentDir.listFiles());
        // Print
        for (File file : files) {
            if (file.isFile()) {
                out.println("file = " + file.getName() + ", size = " + file.length());
            }
        }
        return files;
    }
}
